<template>
  <div>
    <div class="search-div">
      <el-form label-width="70px" size="small">
        <el-row>
          <el-col :span="12">
            <el-form-item label="品牌">
              <el-select
                class="m-2"
                v-model="checkedbrandId"
                placeholder="选择品牌"
                size="small"
                style="width: 100%"
              >
                <el-option
                  v-for="item in brandList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类">
              <el-cascader
                v-model="checkedCateIds"
                :props="categoryProps"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="display:flex">
          <el-button type="primary" size="small" @click="handleSearch">
            搜索
          </el-button>
          <el-button size="small" @click="handleClear">重置</el-button>
        </el-row>
      </el-form>
    </div>

    <div class="tools-div">
      <el-button type="success" size="small" @click="handleShowAddDialog">
        添 加
      </el-button>
    </div>

    <el-table :data="list" style="width: 100%">
      <el-table-column prop="categoryName" label="分类" />
      <el-table-column prop="brandName" label="品牌" />
      <el-table-column prop="logo" label="品牌图标" #default="scope">
        <img :src="scope.row.logo" width="50" />
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" align="center" width="200" #default="scope">
        <el-button
          type="primary"
          size="small"
          @click="handleShowEditDialog(scope.row)"
        >
          修改
        </el-button>
        <el-button type="danger" size="small" @click="handleDelete(scope.row)">
          删除
        </el-button>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[1, 2, 3, 4, 5]"
      layout="total, sizes, prev, pager, next"
      :total="total"
      @size-change="handleChange"
      @current-change="handleChange"
    />
    <!--新增或更新分类品牌的对话框-->
    <div>
      <el-dialog v-model="dialogVisible" title="添加或修改" width="30%">
        <el-form label-width="120px">
          <el-form-item label="品牌">
            <el-select
              v-model="categoryBrand.brandId"
              class="m-2"
              placeholder="选择品牌"
              size="small"
            >
              <el-option
                v-for="item in brandList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="分类">
            <el-cascader
              v-model="categoryBrand.categoryId"
              :props="categoryProps"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSaveOrUpdate">
              提交
            </el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ListAll } from '@/api/brand'
import { GetPage, DeleteById, Save, UpdateById } from '@/api/categoryBrand'
import { listCatesByPid } from '@/api/category'
import { ElMessage, ElMessageBox } from 'element-plus'
//===========================新增1
let dialogVisible = ref(false)
let categoryBrand = ref({})
//提交更新请求
const handleUpdate = async () => {
  await UpdateById(categoryBrand.value)
  ElMessage.success('更新成功')
  dialogVisible.value = false
  //刷新页码
  fetchdata()
}
//更新或增加
const handleSaveOrUpdate = () => {
  if (!categoryBrand.value.categoryId || !categoryBrand.value.brandId) {
    ElMessage.warning('请选择品牌或分类')
    return
  }
  categoryBrand.value.categoryId =
    categoryBrand.value.categoryId[categoryBrand.value.categoryId.length - 1]
  console.log(categoryBrand.value)
  if (categoryBrand.value.id) {
    //更新
    handleUpdate()
  } else {
    //新增
    handleSave()
  }
}
//修改按钮的事件函数：弹出更新对话框
const handleShowEditDialog = row => {
  categoryBrand.value = { id: row.id, brandId: row.brandId }
  dialogVisible.value = true
}
//添加按钮显示对话框事件函数
const handleShowAddDialog = () => {
  categoryBrand.value = {}
  dialogVisible.value = true
}
//新增提交按钮
const handleSave = async () => {
  //提交新增请求
  await Save(categoryBrand.value)
  ElMessage.success('新增成功')
  dialogVisible.value = false
  //刷新页码
  fetchdata()
}
//---------------------------新增2
let checkedbrandId = ref(null)
let checkedCateIds = ref([])
let pageNum = ref(1)
let pageSize = ref(3)
// 分页条数据模型
const total = ref(0)
//搜索条件加载
const ListAllBrands = async () => {
  const { data } = await ListAll()
  brandList.value = data
}
onMounted(() => {
  ListAllBrands()
  fetchdata()
})
//页码改变时查询数据
const handleChange = () => {
  fetchdata()
}
//分页查询
const fetchdata = async () => {
  const { data } = await GetPage(
    pageNum.value,
    pageSize.value,
    categoryBrandDto.value
  )
  console.log(categoryBrandDto.value)
  console.log(data.list)
  list.value = data.list
  total.value = data.total
}

//搜索按钮事件函数
const handleSearch = () => {
  console.log(checkedbrandId.value, checkedCateIds.value)
  //输入搜索条件：组装查询条件
  if (checkedbrandId.value) {
    categoryBrandDto.value.brandId = checkedbrandId.value
  }
  if (checkedCateIds.value.length > 0) {
    categoryBrandDto.value.categoryId =
      checkedCateIds.value[checkedCateIds.value.length - 1]
  }
  fetchdata()
}
let categoryBrandDto = ref({}) //{brandId:checkedbrandId,categoryId:checkedCateIds}
//重置按钮的事件函数
const handleClear = () => {
  categoryBrandDto.value = {}
  checkedbrandId.value = null
  checkedCateIds.value = []
  pageNum.value = 1
  pageSize.value = 3
  fetchdata()
}
//删除按钮的事件函数
const handleDelete = row => {
  ElMessageBox.confirm(
    `您确认删除【${row.brandName}-${row.categoryName}】吗?`,
    '是否继续',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      //异步请求删除id对应的角色
      const { code, message } = await DeleteById(row.id)
      if (+code === 200) {
        ElMessage.success('删除成功')
        fetchdata()
      } else {
        ElMessage.error(message)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
// ================数据模型定义  start ===============================================

// 定义搜索表单数据模型
const brandList = ref([])

const props = {
  lazy: true, //懒加载，必须结合lazyLoad一起使用
  value: 'id',
  label: 'name', //渲染时显示节点的名称
  leaf: 'leaf',
  async lazyLoad(node, resolve) {
    // 加载数据的方法
    if (!node.value) {
      node.value = 0
    }
    const { data } = await listCatesByPid(node.value)
    //处理上面的data集合，判断如果数据有下一级设置leaf属性值为false
    data.forEach(cate => {
      cate.leaf = !cate.hasChildren
    })
    resolve(data) // 返回数据
  },
}
const categoryProps = ref(props)

// 定义表格数据模型
const list = ref([])

// =========   数据模型定义 end======================================================================
</script>

<style scoped>
.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
</style>
